extends CharacterBody2D
class_name ChickenEnemy

@export var stats: PandoraEntity
@onready var animated_sprite_2d: AnimatedSprite2D = %AnimatedSprite2D
@onready var gpu_particles_2d: GPUParticles2D = %GPUParticles2D
@onready var enemy_health_component: EnemyHealthComponent = %EnemyHealthComponent
@onready var sprite : AnimatedSprite2D      = $AnimatedSprite2D

@export var move_speed             : float = 200.0     # 平移动速度
@export var direction_change_interval : float = 2.0    # 随机改变方向的间隔
@export var obstacle_bounce_force     : float = 1.0    # 反弹力度

# 每个关卡基础金币奖励(击杀必得)
const LEVEL_REWARDS := {
	1:  50,  2:  75,  3: 100,  4: 125,  5: 150,
	6: 175,  7: 200,  8: 225,  9: 250, 10: 275,
   11: 300, 12: 325, 13: 350, 14: 375, 15: 400
}

# ────────────────────────────────
# 运行时数据
var direction               : Vector2 = Vector2.ZERO    # 当前移动方向
var last_direction_change   : float   = 2.0             # 距上次改向的累计时间
var bonus_gold              : int     = 0               # 关卡金币奖励
var have_reward             : bool    = true            # 击杀是否掉落

signal gold_earned(amount : int)
signal gold_defeated()


var chicken_stats: PandoraEntity
# ────────────────────────────────
func _ready() -> void:
	## 关卡基础金币
	chicken_stats = stats.instantiate()
	# 监听受击
	enemy_health_component.die.connect(_on_die)
	# 添加到敌人组
	add_to_group("enemy")

	# 保证每次实例随机
	randomize()
	await get_tree().create_timer(10).timeout
	if sprite:
		var tween = create_tween()
		tween.tween_property(sprite, "modulate:a", 0.0, 0.5)
		tween.tween_callback(queue_free)
		
	await get_tree().create_timer(0.5).timeout
	queue_free()

# ────────────────────────────────
# 每帧物理
func _physics_process(delta : float) -> void:
	_periodic_direction_change(delta)
	_random_movement()
	_handle_collision()
	move_and_slide()


# ────────────────────────────────
# 方向相关
func _periodic_direction_change(delta : float) -> void:
	last_direction_change += delta
	if last_direction_change >= direction_change_interval:
		last_direction_change = 0.0
		direction = _get_random_direction()

func _get_random_direction() -> Vector2:
	# 20 % 概率原地不动，其余随机方向
	if randf() < 0.2:
		animated_sprite_2d.play("idle")
		gpu_particles_2d.emitting = false
		return Vector2.ZERO
		
	gpu_particles_2d.emitting = true
	var dir := Vector2(randf_range(-1, 1), randf_range(-1, 1))
	if dir.x > 0:
		animated_sprite_2d.flip_h = true
	if dir.x < 0:
		animated_sprite_2d.flip_h = false
	animated_sprite_2d.play("walk")
	return dir.normalized()

# ────────────────────────────────
# 移动与碰撞
func _random_movement() -> void:
	velocity = direction * move_speed

func _handle_collision() -> void:
	if get_slide_collision_count() == 0:
		return

	# 取第一条碰撞信息，利用法向量做弹射
	var col := get_slide_collision(0)
	var normal : Vector2 = col.get_normal()
	direction = direction.bounce(normal).normalized() * obstacle_bounce_force
	if direction.x > 0:
		animated_sprite_2d.flip_h = true
	if direction.x < 0:
		animated_sprite_2d.flip_h = false
	# 弹射后马上移动一次，避免卡在墙里
	velocity = direction * move_speed

func _on_die() -> void:
	if have_reward:
		_drop_reward()
	emit_signal("gold_defeated")

		# 播放死亡动画
	if sprite:
		var tween = create_tween()
		tween.tween_property(sprite, "modulate:a", 0.0, 0.5)
		tween.tween_callback(queue_free)
		
	await get_tree().create_timer(0.5).timeout
	queue_free()


# ────────────────────────────────
# 掉落逻辑
func _drop_reward() -> void:
	emit_signal("gold_earned", bonus_gold)

	# 额外随机奖励
	var r := randf()
	if r < 0.50:
		# 10 金币
		Utils.set_player_stats_value("gold", 5)
		emit_signal("gold_earned", 5)

	elif r < 0.65:      # 0.50~0.65 → 15 %
		Utils.set_player_stats_value("max_hp", 1)
		Utils.show_fluent_tip("+1 血量")

	elif r < 0.80:      # 0.65~0.80 → 15 %
		Utils.set_player_stats_value("base_damage", 1)      # +1 攻击
		Utils.show_fluent_tip("+1 攻击")

	elif r < 0.95:      # 0.80~0.95 → 15 %
		Utils.set_player_stats_value("max_mp", 1)    # +1 蓝量
		Utils.show_fluent_tip("+1 蓝量")

	else:               # 0.95~1.00 → 5 %
		var raffleResult = RaffleManager._get_skill_reward(1)
		Utils.show_fluent_tip("获得技能%s" % raffleResult.reward_name)


func get_stats():
	return chicken_stats
